package com.example.wechat;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.wechat.database.WeChatDatabaseManager;

public class PublishMomentActivity extends Activity {
    private static final int REQUEST_CODE_PICK_IMAGE = 1;
    private EditText etContent;
    private ImageView imgSelected;
    private Button btnSelectImage, btnPublish;
    private String imagePath = null;
    private WeChatDatabaseManager dbManager;
    private int currentUserId = 1; // 假设当前用户ID为1

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_moment);
        etContent = findViewById(R.id.et_content);
        imgSelected = findViewById(R.id.img_selected);
        btnSelectImage = findViewById(R.id.btn_select_image);
        btnPublish = findViewById(R.id.btn_publish);
        dbManager = new WeChatDatabaseManager(this);
        dbManager.open();
        btnSelectImage.setOnClickListener(v -> pickImage());
        btnPublish.setOnClickListener(v -> publishMoment());
    }

    private void pickImage() {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            imgSelected.setImageURI(selectedImage);
            imgSelected.setVisibility(ImageView.VISIBLE);
            imagePath = selectedImage.toString();
        }
    }

    private void publishMoment() {
        String content = etContent.getText().toString().trim();
        if (TextUtils.isEmpty(content) && imagePath == null) {
            Toast.makeText(this, "内容或图片不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        // 保存到数据库
        dbManager.addMoment(currentUserId, content, imagePath);
        Toast.makeText(this, "发布成功", Toast.LENGTH_SHORT).show();
        finish();
    }
} 